﻿(function () {
    "use strict";

    var layout;
    var r = 3;
    var canvas;

    function drawPhoto(photo) {
        var _x, _y, _w, _h;
        if (photo.width / photo.height > photo.img.width / photo.img.height) {
            _x = 0;
            _y = 0;
            _w = photo.img.width;
            _h = _w * photo.height / photo.width;
        }
        else {
            _h = photo.img.height;
            _w = parseInt(_h * photo.width / photo.height);
            _x = parseInt((photo.img.width - _w) / 2);
            _y = 0;
        }
        var ctx = canvas.getContext("2d");
        ctx.drawImage(photo.img.el[0], _x, _y, _w, _h, photo.left / r, photo.top / r, photo.width / r, photo.height / r);
    }

    function drawText(text) {
        var _size = text['font-size'] / r;
        var ctx = canvas.getContext("2d");
        ctx.font = _size + "px " + text['font-family'];
        ctx.fillStyle = text['color'];

        ctx.fillText(text.value, text.left / r, text.top / r + _size, text.width / r);

        //ctx.rect(text.left / r, text.top / r, text.width / r, text.height / r);
        //ctx.stroke();
    }

    function drawTemplate() {
        function renderTemplate() {
            var ctx = canvas.getContext("2d");
            ctx.drawImage(_template[0], 0, 0, layout.width / r, layout.height / r);
        }

        var _template;
        if (Context.frames[layout.url]) {
            _template = Context.frames[layout.url];
            renderTemplate();
        }
        else {
            _template = $('<img />');
            _template.attr('src', _url);
            _template.onload(renderTemplate);
        }
    }

    WinJS.UI.Pages.define("/pages/preview/preview.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            // TODO: Initialize the page here.
            layout = Context.layout;
            canvas = document.getElementById('card-canvas');
            console.log(layout);
            $('#container').css('width', layout.width / r);
            $('#container').css('height', layout.height / r);
            canvas.width = layout.width / r;
            canvas.height = layout.height / r;

            var i;
            for (i = 0; i < layout.photos.length; i++) {
                drawPhoto(layout.photos[i]);
            }

            drawTemplate();

            for (i = 0; i < layout.texts.length; i++) {
                drawText(layout.texts[i]);
            }

            $('#controls > button').click(function () {
                Context.imgForPurchase = canvas.toDataURL();
                WinJS.Navigation.navigate("/pages/result/result.html");
            });
        }
    });
})();
